#include "list_sorter.h"
#include "index_merger.h"
#include "ICTCLAS2011.h"

#include <new>

void PrintSortList(MergeList* sortList)
{
    int size = sortList->unit_size();
    for(int i = 0; i < size; ++i)
    {
        NOTICE("obj[%d], weight[%d]", sortList->unit(i).id(), sortList->unit(i).weight());
    }
}


int main(int argc, char** argv)
{
    if(argc != 3)
    {
        fprintf(stderr, "usage: query level.\n");
        return -1;
    }
    log_init();
    g_log_context.log_level = LOG_DEBUG;
    char* query = argv[1];
    int level = atoi(argv[2]);
    char* mconf = "merge.ini";
    IniContext iniContext;
    if(iniLoadFromFile(mconf, &iniContext) != 0) 
    {
        FATAL("load conf[%s] is fail!", mconf);
        return -1;
    }
    char* str = iniGetStrValue(NULL, "segment_data_rough", &iniContext);
    if(NULL == str)
    {
        FATAL("error get name[segment_data_rough]");
        return -1;
    }
   int ret = ICTCLAS_Init(str);
    if(ret < 0)
    {
        FATAL("segment init error[%s]", str);
        return -1;
    }
    str = iniGetStrValue(NULL, "index_path", &iniContext);
    if(NULL == str)
    {
        FATAL("Init IndexReader is fail! Index_Path[%s]", str);
        return -1;
    }
    IndexReader indexReader;
    ret = indexReader.Init(str);
    if(ret < 0)
    {
        FATAL("init index_reader is fail!");
        return -1;
    }
    IndexMerger* indexMerger = new(std::nothrow) IndexMerger(&indexReader);
    if(NULL == indexMerger)
    {
        FATAL("new ListMerger is fail!");
        return -1;
    }
   const char* pTerm = ICTCLAS_ParagraphProcess(query, 0);
   SearchTermList* termList = new SearchTermList();
//    TermList termList;
 //   termList.num = 0;
    char* tc = NULL;
    const char* p = pTerm;
    size_t termLen = 0;
    int numTermInfo = 0;
    int numTem = 0;
   // size_t term_szie = sizeof(termList.termInfo[0].term[0].term_str);
    uint64_t sign = 0;
    while(true) 
    {
        tc = strchr(p, ' ');
        if(tc == NULL)
            break;
        termLen = tc-p;
        if(*p == ' '|| termLen == 0)
        {   
            p = tc + 1;
            continue;
        }
        TermUnit* termUnit = termList->add_termunit();
        Term* term = termUnit->add_term();
        term->set_termstr(p, termLen);
        ret = create_sign64(const_cast<char*>(term->termstr().c_str()), term->termstr().length(), &sign);
        term->set_sign(sign);
        term->set_level(level);
        p = tc+1;
    }
    MergeList mergeList;
    ret = indexMerger->MergeIndex(&mergeList, termList);
    if(ret < 0)
    {
        WARNING("query is not found!");
        return -1;
    }
    ListSorter listSorter;
    MergeList* srcList[10];
    srcList[0] = &mergeList;
    MergeList resList;
    ret = listSorter.SortList(srcList, 1, &resList);
    PrintSortList(&resList);
    return 0;
}




















/* vim: set expandtab ts=4 sw=4 sts=4 tw=100: */
